package com.zhiyou.controller;

import com.zhiyou.entity.PowerCenter;
import com.zhiyou.util.DBUtil;
import com.zhiyou.util.PWUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author sanshi
 * @desc
 * @create 2021-09-02 15:12
 */
@WebServlet("/DoAddServlet")
public class DoAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("=======");
        String username=req.getParameter("username");//可以拿到json数据
        System.out.println("username: "+username);
        //连接数据库  进行用户名字的查询
        DBUtil util = new DBUtil();
        String sql = "select * from sys_user where acct = ?";
        Object[] params = {username};
        //也要响应成json形式的数据
        resp.setContentType("text/json; charset=utf-8");//设置响应的数据格式
        PrintWriter out = resp.getWriter();
        // JSONObject jsonobj = new JSONObject();
        //jsonobj.put("response", "success"); // {"response":"success"}
        // jsonobj.put("msg", "ok");
        // out.println(jsonobj);
        boolean exit = util.isExit(sql, params);
        if (!exit){
            out.print("{\"response\":\"success\"}");
        }else{
            out.print("{\"response\":\"defeat\"}");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String addusername = req.getParameter("addusername");
        String addpassword = req.getParameter("addpassword");
        DBUtil util = new DBUtil();
        String sql = "insert into sys_user (acct,pwd) values (?,?)";
        Object[] params = {addusername,addpassword};
        int i = util.updateInfo(sql, params);
        if (i==0){
            //新增失败
            resp.sendRedirect("accountError.jsp");
        }else{
            //新增成功
            session.setAttribute("add","success");
            PWUtil pwUtil = new PWUtil();
            //更新PW表
            Object[] params2 = {addusername};
            String sql2 = "insert into sys_user_chnl (acct) values (?)";
            new DBUtil().updateInfo(sql2, params2);
            List<PowerCenter> pcList = pwUtil.getAllPC3();
            session.setAttribute("pcList",pcList);
            resp.sendRedirect("/page/AccountManagement.jsp");
        }
    }
}
